// 二进制读写文件
#include <stdio.h>
#include <stdlib.h> //为了调用exit()
#include <string.h>

int main()
{
    char *str = "this is the test file.";
    char readbuf[100];

    FILE *fp = NULL;
    fp = fopen("xxq", "wb");
    fwrite(str, sizeof(char), strlen(str) + 1, fp);
    fread(readbuf, sizeof(char), strlen(str) + 1, fp);

    fclose(fp);
    printf("%s\n", readbuf);
    return 0;
}

// file_redu
#define LEN 40

int main(int argc, char *argv[])
{
    FILE *fpin, *fpout;
    int ch;
    char name[LEN]; //用于存储输入文件名
    int count = 0;

    //检查命令行参数
    if (argc < 2)
    {
        fprintf(stderr, "Usage:%s filename\n", argv[0]);
        exit(1); //非正常退出
    }

    //实现输入
    if (fpin = fopen(argv[1], "wb") == NULL)
    {
        fprintf(stderr, "open the file failed\n");
        exit(2); //非正常退出
    }

    //实现输出
    strcpy(name, argv[1]); //把文件名复制到数组中
    strcat(name, ".redu"); //在文件名后添加.redu

    if (fpout = fopen(name, "w") == NULL)
    {
        fprintf(stderr, "can't create output file.\n");
        exit(3); //非正常退出
    }

    //复制数据
    while (ch = getc(fpin) != EOF)
    {
        if (count++ % 3 == 0)
            putc(ch, fpout); //打印每三个字符中的一个
    }

    //收尾工作
    if (fclose(fpin) != 0 || fclose(fpout) != 0)
        fprintf(stderr, "error in closing files.\n");

    return 0;
}
